use crate::logger;
use std::time::Duration;
use tokio::time::interval;

/// 系统监控器，定期记录系统状态
pub struct SystemMonitor {
    interval_duration: Duration,
}

impl SystemMonitor {
    /// 创建新的系统监控器
    pub fn new(interval_minutes: u64) -> Self {
        Self {
            interval_duration: Duration::from_secs(interval_minutes * 60),
        }
    }

    /// 启动系统监控
    pub fn start(&self) {
        let interval_duration = self.interval_duration;
        
        tokio::spawn(async move {
            let mut interval = interval(interval_duration);
            
            loop {
                interval.tick().await;
                Self::log_system_status().await;
            }
        });
        
        logger::log_info("SystemMonitor", &format!("System monitor started with interval: {} minutes", 
                                                   interval_duration.as_secs() / 60));
    }

    /// 记录系统状态
    async fn log_system_status() {
        // 记录内存使用情况
        logger::log_memory_usage();
        
        // 记录线程数量
        if let Ok(thread_count) = get_thread_count() {
            logger::log_info("SystemMonitor", &format!("Active threads: {}", thread_count));
        }
        
        // 记录运行时间
        if let Ok(uptime) = get_process_uptime() {
            logger::log_info("SystemMonitor", &format!("Process uptime: {} seconds", uptime));
        }
    }

    /// 记录应用健康状态
    pub fn log_health_check(component: &str, status: &str, details: &str) {
        logger::log_info("HealthCheck", &format!("component={}, status={}, details={}", 
                                                 component, status, details));
    }
}

/// 获取当前进程的线程数量
fn get_thread_count() -> Result<u32, Box<dyn std::error::Error>> {
    #[cfg(windows)]
    {
        use std::mem;
        
        extern "system" {
            fn GetCurrentProcess() -> *mut std::ffi::c_void;
            fn GetProcessInformation(
                process: *mut std::ffi::c_void,
                info_class: u32,
                info: *mut std::ffi::c_void,
                info_length: u32,
                return_length: *mut u32,
            ) -> i32;
        }
        
        const PROCESS_BASIC_INFORMATION: u32 = 0;
        
        #[repr(C)]
        struct ProcessBasicInformation {
            exit_status: isize,
            peb_base_address: *mut std::ffi::c_void,
            affinity_mask: usize,
            base_priority: isize,
            unique_process_id: usize,
            inherited_from_unique_process_id: usize,
        }
        
        // 简化实现，返回估算值
        Ok(std::thread::available_parallelism()?.get() as u32 * 2)
    }
    
    #[cfg(not(windows))]
    {
        // 对于非Windows系统，返回估算值
        Ok(std::thread::available_parallelism()?.get() as u32)
    }
}

/// 获取进程运行时间（秒）
fn get_process_uptime() -> Result<u64, Box<dyn std::error::Error>> {
    use std::time::{SystemTime, UNIX_EPOCH};
    
    static START_TIME: std::sync::OnceLock<SystemTime> = std::sync::OnceLock::new();
    
    let start_time = START_TIME.get_or_init(|| SystemTime::now());
    let elapsed = start_time.elapsed()?;
    
    Ok(elapsed.as_secs())
}

/// 错误恢复处理器
pub struct ErrorRecovery;

impl ErrorRecovery {
    /// 记录错误并尝试恢复
    pub fn handle_error(component: &str, error: &str, recovery_action: &str) {
        logger::log_api_error(component, "error_recovery", 
                             &format!("error={}, recovery_action={}", error, recovery_action));
    }
    
    /// 记录致命错误
    pub fn handle_fatal_error(component: &str, error: &str) {
        logger::log_fatal_error(error, component);
        
        // 记录当前系统状态
        logger::log_memory_usage();
        
        // 可以在这里添加其他清理逻辑
    }
}

/// 性能监控器
pub struct PerformanceMonitor;

impl PerformanceMonitor {
    /// 记录操作耗时
    pub fn log_operation_time(operation: &str, duration_ms: u64) {
        if duration_ms > 1000 {
            logger::log_warning("Performance", 
                               &format!("Slow operation: {} took {}ms", operation, duration_ms));
        } else {
            logger::log_info("Performance", 
                            &format!("Operation completed: {} took {}ms", operation, duration_ms));
        }
    }
    
    /// 开始计时
    pub fn start_timer() -> std::time::Instant {
        std::time::Instant::now()
    }
    
    /// 结束计时并记录
    pub fn end_timer(start: std::time::Instant, operation: &str) {
        let duration = start.elapsed();
        Self::log_operation_time(operation, duration.as_millis() as u64);
    }
}
